from apps.zhcxkj_center_strategy_comprehensive.test.views.t_strategy_import_filter_allegro import \
    T_strategy_import_filter_allegro
from apps.zhcxkj_center_strategy_comprehensive.test.views.t_strategy_rule_allegro import T_Strategy_rule_allegro
from common.setting import ensure_path_sep
from utils.models import StrategyRuleAllegro
from utils.mongodb_control.batch_by_mongodb import MongoDBByBatch

from utils.mysqlUtils.db_pool import Database
from utils.mysqlUtils.mongodb_utils import MongoDBLink


class ExecuteBadgeCampaignsStrategy:
    zhcxkj_center_strategy_comprehensive_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"),
                                                       "test_jdw_database")
    zhcxkj_center_listing_comprehensive_db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"),
                                                      "test_jdw_database")
    t_sku_strategy_relation_modb = MongoDBLink(
        uri='mongodb://admin:Zhcx?2021@10.158.158.29:27017/?authSource=admin',
        dbname='test_zhcxkj_java_center', coll_name='t_sku_strategy_relation')
    def __init__(self,strategy_id):
        t_strategy_rule_allegro = T_Strategy_rule_allegro.t_strategy_rule_allegro_by_strategy_id(strategy_id)
        for strategy_rule in t_strategy_rule_allegro:
            if StrategyRuleAllegro(**strategy_rule).rule_code == 'product_model':
                self.product_model = StrategyRuleAllegro(**strategy_rule)
            if StrategyRuleAllegro(**strategy_rule).rule_code == 'listing_model':
                self.listing_model = StrategyRuleAllegro(**strategy_rule)
            if StrategyRuleAllegro(**strategy_rule).rule_code == 'badge_campaign_rules' and StrategyRuleAllegro(**strategy_rule).execute_type == 0:
                # 活动报名市场 0 1 2
                self.badge_campaign_rules_0 = StrategyRuleAllegro(**strategy_rule)

            if StrategyRuleAllegro(**strategy_rule).rule_code == 'badge_campaign_rules' and StrategyRuleAllegro(**strategy_rule).execute_type == 1:
                self.badge_campaign_rules_1 = StrategyRuleAllegro(**strategy_rule)

            if StrategyRuleAllegro(**strategy_rule).rule_code == 'badge_campaign_rules' and StrategyRuleAllegro(**strategy_rule).execute_type == 2:
                self.badge_campaign_rules_2 = StrategyRuleAllegro(**strategy_rule)

            if StrategyRuleAllegro(**strategy_rule).rule_code == 'badge_campaign_rules' and StrategyRuleAllegro(**strategy_rule).execute_type == 3:
                self.badge_campaign_rules_3 = StrategyRuleAllegro(**strategy_rule)
            if StrategyRuleAllegro(**strategy_rule).rule_code == 'badge_campaign_rules' and StrategyRuleAllegro(**strategy_rule).execute_type == 4:
                self.badge_campaign_rules_4 = StrategyRuleAllegro(**strategy_rule)
        specify_list = T_strategy_import_filter_allegro.get_t_strategy_import_filter_allegro_by_strategy_id(strategy_id)
        self.specify_list = []
        if len(specify_list):
            self.rule_code = int(specify_list[0][1])
            self.specify_list = [i[0] for i in specify_list]

    def execute_badge_campaigns_strategy(self,source_id):
        """
        t_strategy_allegro
        t_strategy_source_allegro
        t_strategy_rule_allegro
        t_strategy_import_filter_allegro
        t_strategy_source_allegro
        """
        t_allegro_listing_template_detail = f"t_allegro_listing_template_detail_{self.listing_model}"
        t_allegro_listing_template_detail_modb = MongoDBLink(
            uri='mongodb://admin:Zhcx?2021@10.158.158.29:27017/?authSource=admin',
            dbname='test_zhcxkj_java_center', coll_name=t_allegro_listing_template_detail)
        offer_id_set = set()

        if self.specify_list:
            if self.rule_code == 1:
                filters_ObjectId_min = {
                    "$and": [
                        {"sourceId": source_id},
                        {"sourceSku": {"$in": self.specify_list}}
                    ]
                }
            elif self.rule_code == 2:
                filters_ObjectId_min = {
                    "$and": [
                        {"sourceId": source_id},
                        {"offerId": {"$in": list(map(int,self.specify_list))}}
                    ]
                }
            elif self.rule_code == 3:
                filters_ObjectId_min = {
                    "$and": [
                        {"sourceId": source_id},
                        {"sku": {"$in": self.specify_list}}
                    ]
                }
            projection1 = {"_id": 1, "sku": 1,"offerId":1}
            res_id_index = t_allegro_listing_template_detail_modb.select_skip_projection_limit(filters_ObjectId_min,
                                                                                               projection1, "_id",
                                                                                               5000)
            if not res_id_index:
                return
            if self.product_model:
                actual_sku_list = self.filter_t_sku_strategy_relation(res_id_index)

        filters_ObjectId_min = {
            "$and": [
                {"listingTemplateId": self.listing_model},
                {"sourceId": source_id}
            ]
        }
        projection1 = {"_id": 1, "sku": 1,"offerId":1}
        generator = MongoDBByBatch(t_allegro_listing_template_detail_modb).get_data(filters_ObjectId_min,
                                                                                    projection1, 100)
        while True:
            try:
                actual_sku_list = next(generator)
                if self.product_model:
                    actual_sku_list = self.filter_t_sku_strategy_relation(actual_sku_list)

            except StopIteration:
                break
            except Exception as e:
                print(f"非正常推出")
                raise e

    def filter_t_sku_strategy_relation(self,actual_sku_list):
        map_sku_list = list(map(lambda x:x.get('sku'),actual_sku_list))
        filter_sql = {
            "$and": [
                {"sku": {"$in": map_sku_list}},
                {"strategy_relation.strategy_id": self.product_model}
            ]
        }
        projection1 = {"_id": 1, "sku": 1}
        res_id_index = self.t_sku_strategy_relation_modb.select_skip_projection_limit(filter_sql,
                                                                                      projection1, "_id", 5000)
        exist_sku_list = []
        if res_id_index:
            exist_sku_list = list(map(lambda x:x.get('sku'),res_id_index))
        return list(filter(lambda x:x.get('sku') in exist_sku_list,actual_sku_list))

    def cover_to_listing(self,source_id):
        if self.rule_code == 1:
            get_data = f"""
            select offer_id,sku,source_sku
            from test_zhcxkj_center_listing_comprehensive.t_allegro_listing_{source_id%8+1}
            where source_id = %s
            and source_sku in %s
            """
        elif self.rule_code == 2:
            get_data = f"""
            select offer_id,sku,source_sku
            from test_zhcxkj_center_listing_comprehensive.t_allegro_listing_{source_id%8+1}
            where source_id = %s
            and offer_id in %s
            """
        elif self.rule_code == 3:
            get_data = f"""
            select offer_id,sku,source_sku
            from test_zhcxkj_center_listing_comprehensive.t_allegro_listing_{source_id%8+1}
            where source_id = %s
            and sku in %s
            """
        res = self.zhcxkj_center_listing_comprehensive_db.fetch_all_tuple(get_data,())



if __name__ == '__main__':
    ExecuteBadgeCampaignsStrategy(13).execute_badge_campaigns_strategy()